package com.lin.mr.maizilaundry.myapplication;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.SDKInitializer;
import com.lin.mr.maizilaundry.entity.Laundry;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Application为程序的入口，在这里可以初始化各个变量
 */
public class MyApplication extends Application {
    private List<Activity> activities = new LinkedList<Activity>();


    public static Context context;
    //单例化Application
    private static MyApplication appInstance ;

    //返回一个Application实例
    public static MyApplication getInstance() {
        return appInstance;
    }

    //Volley请求队列
    private RequestQueue queue;
    //ImageLoader图片加载器
    private ImageLoader imageLoader;

    //返回图片加载器
    public ImageLoader getImageLoader() {
        return imageLoader;
    }

    /**
     * 全局集合
     */
    public static List<Laundry> laundries = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        appInstance = this;//this赋值给appInstance之后，取得appInstance就相当于MyApplication
        //初始化Volley请求队列
        queue = Volley.newRequestQueue(getApplicationContext());
        //创建ImageLoader图片加载器
        imageLoader = new ImageLoader(queue, new BitmapCache());
        //百度地图初始化
        SDKInitializer.initialize(getApplicationContext());

        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }

    /**
     * 开始请求
     */
    //由于Volley的请求有多种，所以这里采用泛型限定，只限定为请求即可
    public <T> Request<T> startRequest(Request<T> r, Object tag) {
        // 给传来的请求设置TAG，为了知道从哪一个网页请求的
        r.setTag(tag);

        Request<T> request = queue.add(r);

        queue.start();

        return request;
    }
    /**
     * 取消请求
     */
    public void cancelRequest(Object tag){
        queue.cancelAll(tag);
    }

    /**
     * 使用图片缓存
     */
    private class BitmapCache implements ImageLoader.ImageCache {
        private LruCache<String, Bitmap> cache;
        private int maxCache = 10 * 1024 * 1024;//缓存的最大容量

        public BitmapCache() {
            cache = new LruCache<>(maxCache);
        }

        @Override
        public Bitmap getBitmap(String uri) {
            return cache.get(uri);
        }

        @Override
        public void putBitmap(String uri, Bitmap bitmap) {
            cache.put(uri, bitmap);
        }
    }

    public void addActivity(Activity activity) {
        activities.add(activity);
    }

    public void removeActivity(Activity activity) {
        activities.remove(activity);
    }
}
